﻿# -*- coding: utf-8 -*-

from twisted.protocols import basic
from twisted.internet import protocol, reactor

import pygame, zlib
from pygame.locals import *
try:
    import pygame.fastevent as eventmodule
except ImportError:
    import pygame.event as eventmodule

from netDefines import *

class ClientNetwork(basic.LineReceiver):
    """Once connected, send a message, then print the result."""
    
    def connectionMade(self):
        print 'Connection Successful!'
        event = pygame.event.Event(USEREVENT, {'code':CONNECTION_SUCCESS, 'data':self})
        eventmodule.post(event)
        reactor.crash()

    def compressData(self, data):
        return zlib.compress(data)
        
    def decompressData(self, data):
        return zlib.decompress(data)

    def sendMessage(self, code, message):
        print 'sending', code, message
        self.sendLine(code + self.compressData(message))
    
    def dataReceived(self, data):
        print "Got data of length " + str(len(data))
        event = pygame.event.Event(USEREVENT, {'code':data[0:3], 'data':self.decompressData(data[3:])})
        eventmodule.post(event)
    
    def connectionLost(self, reason):
        print "connection lost:", reason
        event = pygame.event.Event(USEREVENT, {'code':CONNECTION_LOST, 'data':self})
        eventmodule.post(event)

class ClientFactory(protocol.ClientFactory):
    protocol = ClientNetwork

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed - goodbye!"
        event = pygame.event.Event(USEREVENT, {'code':CONNECTION_FAILED, 'data':self})
        eventmodule.post(event)
        reactor.stop()
    
    def clientConnectionLost(self, connector, reason):
        print "Connection lost - goodbye!"
        event = pygame.event.Event(USEREVENT, {'code':CONNECTION_LOST, 'data':self})
        eventmodule.post(event)
        reactor.stop()


# this connects the protocol to a server runing on port 8000
def connect(ip, port):
    f = ClientFactory()
    reactor.connectTCP(ip, port, f)
    return reactor
    


